﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Reflection;
using Framework.Domain;
using Framework.Infrastructure;

namespace Framework.EntityFramework
{

    public class EntitiesAssemblyAttribute : System.Attribute
    {
        public string EntitiesAssembly { get; set; }
        public EntitiesAssemblyAttribute(string type)
        {
            EntitiesAssembly = type;
        }
    }
    public static class QueryableCollectionInitializer
    {
        public static void InitializeQueryableCollections(this MSDbContext context, object entity)
        {
            var dbEntity = entity as Entity;
            if (dbEntity != null)
            {
                dbEntity.SetValueByKey("DomainContext", context);
            }
        }
    }

    public class MSDbContext : DbContext
    {
        public MSDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            InitObjectContext();
        }


        protected void InitObjectContext()
        {
            var objectContext = (this as IObjectContextAdapter).ObjectContext;
            if (objectContext != null)
            {
                objectContext.ObjectMaterialized +=
                                 (s, e) => this.InitializeQueryableCollections(e.Entity);

                var attr = this.GetCustomAttribute<EntitiesAssemblyAttribute>();
                if (attr != null)
                {
                    Assembly assembly = Assembly.Load(attr.EntitiesAssembly);
                    objectContext.MetadataWorkspace.LoadFromAssembly(assembly);
                }

            }
        }
    }
}
